﻿using BW.Mes.WinForms.Process.ProcessModel.Model;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace BW.Mes.WinForms.Process
{
    public partial class ProcessUpdateForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _processApiBaseUrl = "http://120.26.197.100:8022";
        private ProcessModel2 _currentModel; // 保存当前编辑的模型

        // 添加部门和车间ID到名称的映射字典
        private Dictionary<long, string> departmentIdToName = new Dictionary<long, string>();
        private Dictionary<string, long> departmentNameToId = new Dictionary<string, long>();
        private Dictionary<long, string> workshopIdToName = new Dictionary<long, string>();
        private Dictionary<string, long> workshopNameToId = new Dictionary<string, long>();
        
        // 声明委托和事件
        public delegate void ProcessUpdatedEventHandler(object sender, EventArgs e);
        public event ProcessUpdatedEventHandler ProcessUpdated;

        // 触发事件的方法
        protected virtual void OnProcessUpdated()
        {
            ProcessUpdated?.Invoke(this, EventArgs.Empty);
        }

        public ProcessUpdateForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        }
        /// <summary>
        /// 构造函数 
        /// </summary>
        /// <param name="model"></param>
        public ProcessUpdateForm(ProcessModel2 model)
        {
            InitializeComponent();
            _currentModel = model; // 保存模型引用
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            if (model != null)
            {
                textEdit1.Text = model.ProcessName;
                textEdit2.Text = model.ProcessExplain;
                textEdit3.Text = model.ProcessDesc;
                textEdit4.Text = model.ProcessHead;
                // 部门和车间信息将在Load事件中处理
                textEdit7.Text = model.ProcessMaterials;
                radioGroup1.SelectedIndex = model.ProcessadEnable ? 1 : 0;
            }
        }


     
        /// <summary>
        /// 修改实体
        /// </summary>
        public class ProcessUpdateModel
        {
            public long Id { get; set; }
            public string processName { get; set; }
            public string processExplain { get; set; }
            public string processDesc { get; set; }
            public string processHead { get; set; }
            public long processDepartment { get; set; }
            public long processworkshop { get; set; }
            public string processMaterials { get; set; }
            public bool processadEnable { get; set; }
        }

        /// <summary>
        /// API返回结果包装类
        /// </summary>
        public class ApiResult<T>
        {
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public T Data { get; set; }
        }

        /// <summary>
        /// 部门实体类
        /// </summary>
        public class Department
        {
            public long Id { get; set; }
            public string departmentName { get; set; }
        }

        /// <summary>
        /// 车间实体类
        /// </summary>
        public class Workshop
        {
            public long Id { get; set; }
            public string workshopName { get; set; }
        }

        private async void ProcessUpdateForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 1. 加载部门和车间数据
                await LoadDepartments();
                await LoadWorkshops();

                // 2. 设置部门和车间下拉框显示名称
                if (_currentModel != null)
                {
                    // 部门ID转换
                    long departmentId = 0;
                    if (long.TryParse(_currentModel.ProcessDepartment.ToString(), out departmentId))
                    {
                        if (departmentIdToName.ContainsKey(departmentId))
                        {
                            comboBoxEdit1.Text = departmentIdToName[departmentId];
                        }
                        else
                        {
                            // 如果在字典中找不到，尝试从数据源获取名称
                            string deptName = await GetDepartmentNameById(departmentId);
                            if (!string.IsNullOrEmpty(deptName))
                            {
                                comboBoxEdit1.Text = deptName;
                                departmentIdToName[departmentId] = deptName;
                            }
                            else
                            {
                                comboBoxEdit1.Text = _currentModel.ProcessDepartment.ToString();
                            }
                        }
                    }
                    else
                    {
                        comboBoxEdit1.Text = _currentModel.ProcessDepartment.ToString();
                    }

                    // 车间ID转换
                    long workshopId = 0;
                    if (long.TryParse(_currentModel.Processworkshop.ToString(), out workshopId))
                    {
                        if (workshopIdToName.ContainsKey(workshopId))
                        {
                            comboBoxEdit2.Text = workshopIdToName[workshopId];
                        }
                        else
                        {
                            // 如果在字典中找不到，尝试从数据源获取名称
                            string workshopName = await GetWorkshopNameById(workshopId);
                            if (!string.IsNullOrEmpty(workshopName))
                            {
                                comboBoxEdit2.Text = workshopName;
                                workshopIdToName[workshopId] = workshopName;
                            }
                            else
                            {
                                comboBoxEdit2.Text = _currentModel.Processworkshop.ToString();
                            }
                        }
                    }
                    else
                    {
                        comboBoxEdit2.Text = _currentModel.Processworkshop.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 通过ID获取部门名称
        /// </summary>
        private async Task<string> GetDepartmentNameById(long Id)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");
                    var response = await client.GetAsync($"/T5/Department/GetById2?id={Id}");

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<Department>>(content);

                        if (result != null && result.Data != null)
                        {
                            return result.Data.departmentName;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取部门名称出错: {ex.Message}");
            }
            return string.Empty;
        }

        /// <summary>
        /// 通过ID获取车间名称
        /// </summary>
        private async Task<string> GetWorkshopNameById(long Id)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");
                    var response = await client.GetAsync($"/T2/Workshop/GetById?id={Id}");

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<Workshop>>(content);

                        if (result != null && result.Data != null)
                        {
                            return result.Data.workshopName;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取车间名称出错: {ex.Message}");
            }
            return string.Empty;
        }

        /// <summary>
        /// 从API获取部门数据并建立映射
        /// </summary>
        private async Task LoadDepartments()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");
                    var response = await client.GetAsync("/T5/Department/ShowDepartments");

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<List<Department>>>(content);

                        if (result != null && result.Data != null)
                        {
                            // 清空现有项
                            comboBoxEdit1.Properties.Items.Clear();
                            departmentNameToId.Clear();
                            departmentIdToName.Clear();

                            // 填充下拉框和字典
                            foreach (var dept in result.Data)
                            {
                                comboBoxEdit1.Properties.Items.Add(dept.departmentName);
                                departmentNameToId[dept.departmentName] = dept.Id;
                                departmentIdToName[dept.Id] = dept.departmentName;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"获取部门数据出错: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 从API获取车间数据并建立映射
        /// </summary>
        private async Task LoadWorkshops()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");
                    var response = await client.GetAsync("/T2/Workshop/ShowWorkshop");

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<List<Workshop>>>(content);

                        if (result != null && result.Data != null)
                        {
                            // 清空现有项
                            comboBoxEdit2.Properties.Items.Clear();
                            workshopNameToId.Clear();
                            workshopIdToName.Clear();

                            // 填充下拉框和字典
                            foreach (var workshop in result.Data)
                            {
                                comboBoxEdit2.Properties.Items.Add(workshop.workshopName);
                                workshopNameToId[workshop.workshopName] = workshop.Id;
                                workshopIdToName[workshop.Id] = workshop.workshopName;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"获取车间数据出错: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 修改按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(textEdit1.Text))
            {
                XtraMessageBox.Show("请输入工序名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textEdit1.Focus();
                return;
            }

            // 获取选中部门和车间的ID
            long departmentId = 0;
            if (!string.IsNullOrEmpty(comboBoxEdit1.Text) && departmentNameToId.ContainsKey(comboBoxEdit1.Text))
            {
                departmentId = departmentNameToId[comboBoxEdit1.Text];
            }

            long workshopId = 0;
            if (!string.IsNullOrEmpty(comboBoxEdit2.Text) && workshopNameToId.ContainsKey(comboBoxEdit2.Text))
            {
                workshopId = workshopNameToId[comboBoxEdit2.Text];
            }

            // 构建更新模型
            var updateModel = new ProcessUpdateModel
            {
                Id = _currentModel.Id, // 使用当前模型的ID
                processName = textEdit1.Text.Trim(),
                processExplain = textEdit2.Text.Trim(),
                processDesc = textEdit3.Text.Trim(),
                processHead = textEdit4.Text.Trim(),
                processDepartment = departmentId,
                processworkshop = workshopId,
                processMaterials = textEdit7.Text.Trim(),
                processadEnable = radioGroup1.SelectedIndex == 1 // 1对应"是"，0对应"否"
            };

            // 发送更新请求
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_processApiBaseUrl);

                // 创建JSON数据
                var json = JsonConvert.SerializeObject(updateModel);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                // 发送PUT请求进行更新
                var response = await client.PostAsync("/T5/ProcessModel/UpdateProcessModel", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("更新成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 触发更新成功事件
                    OnProcessUpdated();
                    
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    var errorMessage = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"更新失败：{response.ReasonPhrase}\n{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            // 重置为原始数据
            if (_currentModel != null)
            {
                textEdit1.Text = _currentModel.ProcessName;
                textEdit2.Text = _currentModel.ProcessExplain;
                textEdit3.Text = _currentModel.ProcessDesc;
                textEdit4.Text = _currentModel.ProcessHead;

                // 部门和车间使用ID查找名称
                long departmentId;
                if (long.TryParse(_currentModel.ProcessDepartment.ToString(), out departmentId)
                    && departmentIdToName.ContainsKey(departmentId))
                {
                    comboBoxEdit1.Text = departmentIdToName[departmentId];
                }
                else
                {
                    comboBoxEdit1.Text = _currentModel.ProcessDepartment;
                }

                long workshopId;
                if (long.TryParse(_currentModel.Processworkshop.ToString(), out workshopId)
                    && workshopIdToName.ContainsKey(workshopId))
                {
                    comboBoxEdit2.Text = workshopIdToName[workshopId];
                }
                else
                {
                    comboBoxEdit2.Text = _currentModel.Processworkshop;
                }

                textEdit7.Text = _currentModel.ProcessMaterials;
                radioGroup1.SelectedIndex = _currentModel.ProcessadEnable ? 1 : 0;
            }
        }
    }
}